package com.cn.xiaonuo.slbfinances.slexapply.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.SystemConstant;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.FileUtil;
import com.cn.xiaonuo.common.utils.QiniuUtil;
import com.cn.xiaonuo.common.utils.StringUtils;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.slexapply.entity.SlFileInfo;
import com.cn.xiaonuo.slbfinances.slexapply.entity.SlBUser;
import com.cn.xiaonuo.slbfinances.slexapply.entity.SlUserReal;
import com.cn.xiaonuo.slbfinances.slexapply.entity.SlUserRealLog;
import com.cn.xiaonuo.slbfinances.slexapply.mapper.*;
import com.cn.xiaonuo.slbfinances.slexapply.service.IExApplyBuyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ExApplyBuyServiceImpl extends ServiceImpl<ExApplyBuyMapper, String> implements IExApplyBuyService {

    @Resource
    private ExApplyBuyMapper exApplyBuyMapper;
    @Resource
    private SlUserRealsMapper slUserRealMapper;
    @Resource
    private SlUserRealLogMapper slUserRealLogMapper;
    @Resource
    private SlFileInfoMapper slFileInfoMapper;
    @Resource
    private SlBUserMapper slBUserMapper;
    @Resource
    private SlbCmSystemMapper slbCmSystemMapper;


    @Override
    //文交记录查询--内盘查询--用户实名制--数据列表
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage queryRealUser(String userReal_id,
                                         String userReal_name,
                                         String userReal_phone,
                                         String check_state,
                                         String shop_name,
                                         String shop_id,
                                         Integer pageNo,
                                         Integer pageSize,
                                         String needPage) {
        BusinessMessage message = new BusinessMessage();
        try {
            //0.不分页查询所有真实用户
            if ("1".equals(needPage)) {
                List<Map<String, Object>> realListPage = exApplyBuyMapper.queryRealUser(userReal_id, userReal_name, userReal_phone, check_state, shop_name, shop_id);//查询实名制用户

                message.setData(realListPage);
                message.setSuccess(true);
                message.setMessage("查询成功");
                return message;
            }

            //1.分页参数设置
            if (null == pageNo || pageNo <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || pageSize <= 1) {
                pageSize = 10;
            }

            //2.分页查询
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> headmanList = exApplyBuyMapper.queryRealUser(userReal_id, userReal_name, userReal_phone, check_state, shop_name, shop_id);//查询实名制用户
            PageInfo<Map<String, Object>> data = new PageInfo<>(headmanList);

            //3.返回数据
            message.setData(data);
            message.setSuccess(true);
            message.setMessage("查询成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }

    //文交记录查询--内盘查询--用户实名制--添加用户/编辑用户
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage addRealUser(String login_user_id,
                                       String apply_user_id,
                                       String real_name,
                                       String identity_card,
                                       MultipartFile hand_identity_card_image,
                                       String bank_card,
                                       String open_branch_bank,
                                       String bankCode,
                                       String bankAcctType,
                                       String provCode,
                                       String areaCode,
                                       String reservePhone) {
        BusinessMessage message = new BusinessMessage();
        try {
            //1.验证必填参数不能为空
            if (StringUtils.isBlank(login_user_id) || StringUtils.isBlank(apply_user_id)) {
                message.setSuccess(false);
                message.setMessage("必填参数不能为空");
                return message;
            }

            //2.验证参数是否正确
            SlBUser loginUser = slBUserMapper.selectById (login_user_id);
            if (login_user_id == null) {
                message.setSuccess(false);
                message.setMessage("当前登录人不存在");
                return message;
            }

            SlBUser applyUser = slBUserMapper.selectById(apply_user_id);
            if (applyUser == null) {
                message.setSuccess(false);
                message.setMessage("该用户不存在");
                return message;
            }

            //3.业务逻辑--判断是新增还是修改
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.setEntity(new SlUserReal() {{
                setUserId(applyUser.getId());
            }});
            SlUserReal slUserReal = slUserRealMapper.selectOne(queryWrapper);
            if (slUserReal == null) {
                message = insertRealUser(loginUser,
                        applyUser,
                        real_name,
                        identity_card,
                        hand_identity_card_image,
                        bank_card,
                        open_branch_bank,
                        bankCode,
                        bankAcctType,
                        provCode,
                        areaCode,
                        reservePhone);
            } else {
                message = updateRealUser(
                        loginUser,
                        slUserReal,
                        real_name,
                        identity_card,
                        hand_identity_card_image,
                        bank_card, open_branch_bank,
                        bankCode,
                        bankAcctType,
                        provCode,
                        areaCode,
                        reservePhone);
            }

            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }

    @NotNull
    public static SlFileInfo getFileInfo(@NotNull MultipartFile file) throws Exception {
        String md5 = FileUtil.fileMd5(file.getInputStream());
        SlFileInfo fileInfo = new SlFileInfo();
        fileInfo.setMd5(md5);// 将文件的md5设置为文件表的id
        fileInfo.setSourceName(file.getOriginalFilename());
        fileInfo.setContentType(file.getContentType());
        fileInfo.setSize(file.getSize());
        fileInfo.setCreatedAt(new Date());
        return fileInfo;
    }

    /**
     * 上传文件，并返回图片URL、图片名称和图片的宽度和高度
     *
     * @param type 文件类型，例如用于头像、商品等
     * @param file 文件
     * @return 文件URL、图片宽度、高度
     */
    public JSONObject newUpload(String type, MultipartFile file) {
        String fileUrl = "";
        try {
            SlFileInfo fileInfo = getFileInfo(file);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.setEntity(new SlFileInfo() {{
                setMd5(fileInfo.getMd5());
            }});
            SlFileInfo slFileInfo = slFileInfoMapper.selectOne(queryWrapper);
            if (null != slFileInfo) {
                fileUrl = slFileInfo.getPath();
                JSONObject data = new JSONObject();
                data.put("fileName", fileUrl);
                data.put("fileUrl", fileUrl);
                return data;
            }
            fileUrl = QiniuUtil.uploadFile(file);
            fileInfo.setPath(fileUrl);
            slFileInfoMapper.insert(fileInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject data = new JSONObject();
        //data.put("fileName", file.getName());//以前有的地方用的是“fileName”，故改为和"fileUrl"一样的值
        data.put("fileName", fileUrl);
        data.put("fileUrl", fileUrl);

        return data;
    }

    //11-1 实名制--新增
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage insertRealUser(SlBUser loginUser,
                                          SlBUser applyUser,
                                          String real_name,
                                          String identity_card,
                                          MultipartFile hand_identity_card_image,
                                          String bank_card,
                                          String open_branch_bank,
                                          String bankCode,
                                          String bankAcctType,
                                          String provCode,
                                          String areaCode,
                                          String reservePhone) {

        BusinessMessage message = new BusinessMessage();
        try {
            if (StringUtils.isBlank(reservePhone)) {
                message.setMessage("预留手机号码不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(real_name)) {
                message.setMessage("真实姓名不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(identity_card)) {
                message.setMessage("身份证号码不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(bank_card)) {
                message.setMessage("银行卡号不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(bankCode)) {
                message.setMessage("请选择银行");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(provCode)) {
                message.setMessage("请选择省");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(areaCode)) {
                message.setMessage("请选择市");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            //1.写数据
            SlUserReal slUserReal = new SlUserReal();
            slUserReal.setBankCode(bankCode);
            slUserReal.setBankAcctType(bankAcctType);
            slUserReal.setProvCode(provCode);
            slUserReal.setAreaCode(areaCode);
            slUserReal.setReservePhone(reservePhone);

            slUserReal.setUserId(applyUser.getId());//申请用户id
            slUserReal.setCheckState(-1);//审核状态
            slUserReal.setCreateTime(SystemConstant.SDF.format(new Date()));//创建时间
            slUserReal.setUpdateTime(SystemConstant.SDF.format(new Date()));//修改时间
            if (StringUtils.isNotBlank(real_name)) {
                slUserReal.setRealName(real_name);//真实姓名
            }
            if (StringUtils.isNotBlank(identity_card)) {
                slUserReal.setIdentityCard(identity_card);//身份证号码
            }
            if (hand_identity_card_image != null) {
                JSONObject jsonObject = newUpload(null, hand_identity_card_image);
                slUserReal.setHandIdentityCardImage(jsonObject.getString("fileUrl"));//手持身份证
            }
            if (StringUtils.isNotBlank(bank_card)) {
                slUserReal.setBankCard(bank_card);//银行卡号
            }
            if (StringUtils.isNotBlank(open_branch_bank)) {
                slUserReal.setOpenBranchBank(open_branch_bank);//开户支行
            }
            slUserRealMapper.insert(slUserReal);

            //2.写日志
            SlUserRealLog slUserRealLog = new SlUserRealLog();
            slUserRealLog.setUserId(applyUser.getId());//申请用户id
            slUserRealLog.setCheckState(-1);//审核状态
            slUserRealLog.setRecordUserId(loginUser.getId());//记录人
            if (StringUtils.isNotBlank(real_name)) {
                slUserRealLog.setRealName(real_name);//真实姓名
            }
            if (StringUtils.isNotBlank(identity_card)) {
                slUserRealLog.setIdentityCard(identity_card);//身份证号码
            }
            if (hand_identity_card_image != null) {
                JSONObject jsonObject = newUpload(null, hand_identity_card_image);
                slUserRealLog.setHandIdentityCardImage(jsonObject.getString("fileUrl"));//手持身份证
            }
            if (StringUtils.isNotBlank(bank_card)) {
                slUserRealLog.setBankCard(bank_card);//银行卡号
            }
            if (StringUtils.isNotBlank(open_branch_bank)) {
                slUserRealLog.setOpenBranchBank(open_branch_bank);//开户支行
            }
            slUserRealLogMapper.insert(slUserRealLog);

        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
            return message;
        }
        return message;
    }

    //11-2 实名制--修改 原则上不能修改银行卡号
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage updateRealUser(SlBUser loginUser,
                                          SlUserReal slUserReal,
                                          String real_name,
                                          String identity_card,
                                          MultipartFile hand_identity_card_image,
                                          String bank_card,
                                          String open_branch_bank,
                                          String bankCode,
                                          String bankAcctType,
                                          String provCode,
                                          String areaCode,
                                          String reservePhone) {
        BusinessMessage message = new BusinessMessage();
        try {
            if (StringUtils.isBlank(reservePhone)) {
                message.setMessage("预留手机号码不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(real_name)) {
                message.setMessage("真实姓名不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(identity_card)) {
                message.setMessage("身份证号码不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(bank_card)) {
                message.setMessage("银行卡号不能为空");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(bankCode)) {
                message.setMessage("请选择银行");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(provCode)) {
                message.setMessage("请选择省");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }
            if (StringUtils.isBlank(areaCode)) {
                message.setMessage("请选择市");
                message.setCode("-1");
                message.setSuccess(false);
                return message;
            }

            //0.审核通过后不能再修改
//            if (slUserReal.getCheckState() == 1) {
//                message.setSuccess(false);
//                message.setMsg("已经审核通过，不能再修改");
//                return message;
//            }

            //1.修改数据
            slUserReal.setBankCode(bankCode);
            slUserReal.setBankAcctType(bankAcctType);
            slUserReal.setProvCode(provCode);
            slUserReal.setAreaCode(areaCode);
            slUserReal.setReservePhone(reservePhone);

            slUserReal.setCheckState(-1);//审核状态
            slUserReal.setUpdateTime(SystemConstant.SDF.format(new Date()));//修改时间
            if (StringUtils.isNotBlank(real_name)) {
                slUserReal.setRealName(real_name);//真实姓名
            }
            if (StringUtils.isNotBlank(identity_card)) {
                slUserReal.setIdentityCard(identity_card);//身份证号码
            }
            if (hand_identity_card_image != null) {
                JSONObject jsonObject = newUpload(null, hand_identity_card_image);
                slUserReal.setHandIdentityCardImage(jsonObject.getString("fileUrl"));//手持身份证
            }
            if (StringUtils.isNotBlank(bank_card)) {
                slUserReal.setBankCard(bank_card);//银行卡号
            }
            if (StringUtils.isNotBlank(open_branch_bank)) {
                slUserReal.setOpenBranchBank(open_branch_bank);//开户支行
            }
            slUserRealMapper.updateById(slUserReal);

            //2.写日志
            SlUserRealLog slUserRealLog = new SlUserRealLog();
            slUserRealLog.setUserId(slUserReal.getUserId());//申请用户id
            slUserRealLog.setCheckState(-1);//审核状态
            slUserRealLog.setRecordUserId(loginUser.getId());//记录人
            if (StringUtils.isNotBlank(real_name)) {
                slUserRealLog.setRealName(real_name);//真实姓名
            } else {
                slUserRealLog.setRealName(slUserReal.getRealName());
            }
            if (StringUtils.isNotBlank(identity_card)) {
                slUserRealLog.setIdentityCard(identity_card);//身份证号码
            } else {
                slUserRealLog.setIdentityCard(slUserReal.getIdentityCard());
            }
            if (hand_identity_card_image != null) {
                JSONObject jsonObject = newUpload(null, hand_identity_card_image);
                slUserRealLog.setHandIdentityCardImage(jsonObject.getString("fileUrl"));//手持身份证
            } else {
                slUserRealLog.setHandIdentityCardImage(slUserReal.getHandIdentityCardImage());
            }
            if (StringUtils.isNotBlank(bank_card)) {
                //slUserRealLog.setBankCard(bank_card);//银行卡号，原则上不能改卡号
            } else {
                slUserRealLog.setBankCard(slUserReal.getBankCard());
            }
            if (StringUtils.isNotBlank(open_branch_bank)) {
                slUserRealLog.setOpenBranchBank(open_branch_bank);//开户支行
            } else {
                slUserRealLog.setOpenBranchBank(slUserReal.getOpenBranchBank());
            }
            slUserRealLogMapper.insert(slUserRealLog);


        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
            return message;
        }
        return message;
    }


    //文交记录查询--内盘查询--用户实名制--拒绝/通过
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage checkRealUser(Integer check_userReal_id, Integer check_check_state) {
        BusinessMessage message = new BusinessMessage();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.setEntity(new SlUserReal() {{
                setUserId(check_userReal_id);
            }});
            SlUserReal slUserReal = slUserRealMapper.selectOne(queryWrapper);

            slUserReal.setCheckState(check_check_state);

            slUserRealMapper.updateById(slUserReal);
            //3.返回数据
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }

    //文交记录查询--内盘查--文交商城赠送酒交易明细--统计所有用户
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage queryUserWine(String wjs_user_id,
                                         String user_id,
                                         String user_phone,
                                         String user_name,
                                         Integer aging_or_not,
                                         Integer pageNo,
                                         Integer pageSize) {
        BusinessMessage message = new BusinessMessage();
        try {
            //1.查询出团队长，不分页
            if (aging_or_not == 0) {
                List<Map<String, Object>> allHeadman = exApplyBuyMapper.queryUserWine(wjs_user_id, user_id, user_phone, user_name);

                message.setData(allHeadman);
                message.setSuccess(true);
                message.setMessage("查询成功");
                return message;
            }

            //2.查询出团队长，分页
            if (null == pageNo || pageNo <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || pageSize <= 1) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> headmanList = exApplyBuyMapper.queryUserWine(wjs_user_id, user_id, user_phone, user_name);
            PageInfo<Map<String, Object>> data = new PageInfo<>(headmanList);

            message.setData(data);
            message.setSuccess(true);
            message.setMessage("查询成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("查询失败");
            return message;
        }
    }

    //文交记录查询--内盘查询--求购转让记录
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage purchaseTransferRecord(Integer pageNo,
                                                  Integer pageSize,
                                                  String consigneeName,
                                                  String remark,
                                                  String payment_state,
                                                  String id,
                                                  String startTime,
                                                  String endTime,
                                                  String user_id,
                                                  String serial_number,
                                                  String startConfirmTime,
                                                  String endConfirmTime,
                                                  Integer flg,
                                                  Integer isFirst) {
        BusinessMessage message=new BusinessMessage();
        //0.时间转换，时间戳转年月日
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(startTime)) {
            startTime = sdf.format(new Date(new Long(startTime)));
        }
        if (StringUtils.isNotBlank(endTime)) {
            endTime = sdf.format(new Date(new Long(endTime)));
        }
        if (StringUtils.isNotBlank(startConfirmTime)) {
            startConfirmTime = sdf.format(new Date(new Long(startConfirmTime)));
        }
        if (StringUtils.isNotBlank(endConfirmTime)) {
            endConfirmTime = sdf.format(new Date(new Long(endConfirmTime)));
        }
        if (null == pageNo || pageNo <= 1) {
            pageNo = 1;
        }
        if (null == pageSize || pageSize <= 1) {
            pageSize = 10;
        }
        // 设置分页参数
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> maps = slbCmSystemMapper.purchaseTransferRecord( consigneeName,
                remark,
                payment_state,
                id,
                startTime,
                endTime,user_id,serial_number,startConfirmTime,endConfirmTime,flg,isFirst);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(maps);
        if(maps.size()>0){
            message.setSuccess(true);
            message.setMessage("查询数据成功");
            message.setData(pageInfo);
            return message;
        }else{
            message.setData(pageInfo);
            message.setMessage("没有查询到数据");
            message.setSuccess(false);
            return message;
        }
    }

}
